package cn.buddha.jec.util;

import cn.hutool.core.util.StrUtil;
import com.beust.jcommander.Parameter;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.io.File;

/**
 * @author shihao
 * @description 图片识别
 */
public class TongTesseractUtils {

    public static String parserImage(ParameterParser parameterParser, String imageFileName) {
        ITesseract iTesseract = new Tesseract();
        iTesseract.setDatapath(parameterParser.getDataPath());
        iTesseract.setLanguage(parameterParser.getLanguage());

        File imageFile = new File(imageFileName);
        try {
            return iTesseract.doOCR(imageFile);
        } catch (TesseractException e) {
            throw TongBusinessUtils.createBusinessException("TE-00102", "图片识别失败!");
        }
    }

}

@Slf4j
@Getter
class ParameterParser {

    private static final String TESSERACT_HOME = "TESSERACT_HOME";

    @Parameter(names = {"--dataPath", "-d"}, description = "tessdata训练库语言包地址", order = 1)
    private String dataPath;

    @Parameter(names = {"--language", "-l"}, description = "如果需要识别英文之外的语种，则需要指定")
    private String language;

    ParameterParser(String dataPath, String language) {
        this.dataPath = dataPath;
        this.language = language;

        if (TongStringUtils.isEmpty(this.language)) {
            throw TongBusinessUtils.createBusinessException("TE-00101", "请输入识别语言!");
        }

        if (TongStringUtils.isEmpty(this.dataPath)) {
            String tesseractHome = System.getenv(TESSERACT_HOME);

            if (TongStringUtils.isEmpty(tesseractHome)) {
                throw TongBusinessUtils.createBusinessException("TE-00102",
                        StrUtil.format("请配置环境变量[{}]", TESSERACT_HOME));
            }

            tesseractHome = tesseractHome.trim();
            if (!tesseractHome.endsWith(File.separator)) {
                tesseractHome = tesseractHome.concat(File.separator);
            }

            this.dataPath = tesseractHome.concat("tessdata");
        }
    }

}
